<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/6/3
 * Time: 14:08
 */

namespace app\admin\controller\shop;


use app\admin\BaseController;
use app\admin\model\Admin;
use app\admin\model\ShopRelationCategory;
use app\admin\model\ShopWithdraw;
use app\admin\model\Warehouse;
use app\api\model\ProductOrder;
use app\common\controller\DateCommon;
use app\lib\exception\ExistException;
use app\lib\exception\FailedException;
use app\lib\exception\NoJurisdiction;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\Validate\ActionMustPositiveValidate;
use app\Validate\CreateShopValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;
use app\Validate\WithdrawValidate;
use think\Db;
use think\Exception;
use think\Request;
use app\admin\model\Shop as ShopModel;

class Shop extends BaseController {
    /**
     * 新增商家
     * @param Request $request
     * @return \think\response\Json
     * @throws Exception
     * @throws \app\lib\exception\ParameterException
     */
    public function createShop(Request $request){
        (new CreateShopValidate())->goCheck();
        $shopInfo = $request->post();
        $shopInfo['number'] = getRandNumber(8);
        $category = $shopInfo['category'];
        $shopInfo['status'] =2;//后台添加的商家默认状态为2
        unset($shopInfo['category']);
        $relationData = [];
        try{
            Db::startTrans();
            $existShop = ShopModel::searchShopByPhone($shopInfo['phone']);
            if(!empty($existShop)){
                throw new ExistException(['msg' => '商家已存在']);
            }else{
                $shop = ShopModel::createShop($shopInfo);
                if(!empty($shop)){
                    $shopId = $shop->id;
                    foreach ($category as $value){
                        $data = [
                            'shop_id' => $shopId,
                            'category_id' =>$value
                        ];
                        array_push($relationData,$data);
                    }
                    $relation = (new ShopRelationCategory())->saveAll($relationData);

                    if(!empty($relation)){
                        //添加商家成功之后 线上商家和品牌商是要建立自己的一个仓库
                        if($shopInfo['type'] == 2 || $shopInfo['type'] == 1){
                            $res= (new Warehouse())->addWarehouse($shopId,$shopInfo['name']);
                            if(!$res){
                                Db::rollback();
                                throw new FailedException([ 'msg' => '增加仓库失败，请重试']);
                            }
                        }
                        Db::commit();
                        return writeJson(200,[]);
                    }else{
                        Db::rollback();
                        throw new FailedException(['msg' => '新增商家失败，请重试']);
                    }
                }
            }
        }catch (Exception $exception){
            Db::rollback();
            throw  $exception;
        }
    }

    /**
     * 修改商家
     * @param Request $request
     * @return \think\response\Json
     * @throws Exception
     * @throws \app\lib\exception\ParameterException
     */
    public function editShop(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        if(!isset($post['name'])){
            throw new ParameterException(['msg'=>'缺少商家名称']);
        }
        if(!isset($post['summary'])){
            throw new ParameterException(['msg'=>'缺少商家简介']);
        }
        if(!isset($post['pick_address'])){
            throw new ParameterException(['msg'=>'缺少提货地址']);
        }
        $new = [
          'id'=>$post['id'],
          'name'=>$post['name'],
          'pick_address'=>$post['pick_address'],
          'summary' =>$post['summary']
        ];
        $res = (new \app\admin\model\Shop())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200);
    }

    /**
     * 修改商家
     * @param Request $request
     * @return \think\response\Json
     * @throws Exception
     * @throws \app\lib\exception\ParameterException
     */
    public function changAccount(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        if(!isset($post['account_id'])){
            throw new ParameterException(['msg'=>'缺少账号id']);
        }
        $count = (new Admin())->getCount([['id','eq',$post['account_id']],['uid','eq',0]]);
        if($count==0){
            throw new ParameterException(['msg'=>'账号已绑定']);
        }
        $new = [
            'id'=>$post['account_id'],
            'uid'=>$post['id'],
        ];
        $res = (new Admin())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'操作失败']);
        }
        return writeJson(200);
    }

    /**
     * 删除商家
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function deleteShop(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $res =  (new \app\admin\model\Shop())->where("id",$post['id'])->setField("delete_time",time());
        if($res){
            return writeJson(200,[],'操作成功');
        }
        return writeJson(500,[],'操作失败');
    }

    /**
     * 商家列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function shopList(Request $request){
        (new PageMustValidate())->goCheck();
        //验证是否传了商家的id
        $post = $request->post();
        $where =[];
        if(isset($post['type'])&&$post['type']!=""){ $where[] = ['type','eq',$post['type']]; }
        $where = addWhere($post,['phone'=>"",'name'=>''],$where,2);//商家名称和手机号码
        $where = addWhere($post,['status'=>"",],$where,1);//发布状态
        //交易额的条件
        if(isset($post['min_amount'])&&isset($post['max_amount'])&&$post['min_amount']!=""&&$post['max_amount']!=""){
            $where[] = ['amount','between',[$post['min_amount'],$post['max_amount']]];
        }elseif (isset($post['min_amount'])&&$post['min_amount']!=""){
            $where[] = ['amount','egt',$post['min_amount']];
        }elseif (isset($post['max_amount'])&&$post['max_amount']!=""){
            $where[] = ['amount','elt',$post['max_amount']];
        }
        $count = (new \app\admin\model\Shop())->getCount($where);
        $where['page'] = $post['page'];
        $list =  (new \app\admin\model\Shop())->wechatList($where,"*","id desc",$post['page_number']);
        foreach ($list as &$value){
            $value['account_id'] = (new Admin())->where('uid',$value['id'])->value("id");
            $value['product_number'] = (new \app\admin\model\Product())->where('uid',$value['id'])->count();
            $value['order_number'] = (new ProductOrder())->where('uid',$value['id'])->count();
            $value['categoryList'] = (new ShopRelationCategory())->selectListWith("category_name",[['shop_id','eq',$value['id']]],"*","category_id");
        }
        return writeJson(200,['list'=>$list,'count'=>$count]);
    }

    /**
     * 获取全部商家列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getShopList(Request $request){
        $post = $request->post();
        $where = [];
        if(isset($post['type'])&&$post['type']!=""){ $where[] = ['type','eq',$post['type']]; }
        $where = addWhere($post,['status'=>"",],$where,1);//发布状态
        $count = (new \app\admin\model\Shop())->getCount($where);
        $list =  (new \app\admin\model\Shop())->where($where)->order("id desc")->select()->toArray();
        return writeJson(200,['list'=>$list,'count'=>$count]);
    }

    /**
     * 商家详情
     * @param Request $request
     * @return \think\response\Json
     * @throws NoJurisdiction
     * @throws NotFoundException
     * @throws ParameterException
     */
    public function shop_detail(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $admin = $this->admin;
        if($admin['account_type']==2){//如果是商家账号
            if($post['id']!=$admin['uid']){
                throw new NoJurisdiction();
            }
        }
        $detail = (new \app\admin\model\Shop())->findOne([['id','eq',$post['id']]]);
        if(!$detail){
            throw new NotFoundException(['msg'=>'商家不存在']);
        }
        $detail['logo'] = imgUrlToAbsolute($detail['logo']);
        $detail['hand_id_card'] = imgUrlToAbsolute($detail['hand_id_card']);
        $detail['back_id_card'] = imgUrlToAbsolute($detail['back_id_card']);
        $detail['front_id_card'] = imgUrlToAbsolute($detail['front_id_card']);
        $detail['license'] = imgUrlToAbsolute($detail['license']);
        $where[]= ['shop_id','eq',$detail['id']];
        $detail['category'] = (new ShopRelationCategory())->selectListWith("categoryName", $where,"*","category_id");
        return writeJson(200,['detail'=>$detail]);
    }

    /**
     * 商家封停 和取消封停
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws ParameterException
     * @throws FailedException
     */
    public function shopAction(Request $request){
        (new IdMustPositive())->goCheck();
        (new ActionMustPositiveValidate())->goCheck();
        $post = $request->post();
        $where = [['id','eq',$post['id']]];
        $shop = (new \app\admin\model\Shop())->findOne($where);

        if(!$shop){ throw new NotFoundException(['msg'=>'商家信息不存在']); }
        if($post['action_type']=="check"){
            $new = [
                'id'=>$post['id'],
                'use_status'=>$post['check_status']
            ];
            $res = (new \app\api\model\Shop())->dataUpdate($new);
            if(!$res){ throw new FailedException(['msg'=>'操作失败']);}
            return writeJson(200);
        }

    }

    /**
     * 商家审核列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function shopNoCheckList(Request $request){
        (new PageMustValidate())->goCheck();
        //验证是否传了商家的id
        $post = $request->post();
        $where =[];
        $where[] = ['status','eq',0];//未审核的消息
        if(isset($post['type'])&&$post['type']!=""){
            $where[] = ['type','eq',$post['type']];
        }
        if(isset($post['category_id'])&&$post['category_id']!=""){//未审核商家的列表
            $shop_list = (new ShopRelationCategory())->where('category_id',$post['category_id'])->column("shop_id");
            $where[] = ['id','in',$shop_list];
        }
        $where = addWhere($post,['phone'=>"",'name'=>''],$where,2);//商家名称和手机号码
        $where = addWhere($post,['status'=>"",],$where,1);//发布状态

        //交易额的条件
        $DateCommon = new DateCommon();
        if(isset($post['min_amount'])&&isset($post['max_amount'])&&$post['min_amount']!=""&&$post['max_amount']!=""){
            $post['min_amount'] = $DateCommon->OutUnixByTime($post['min_amount']);
            $post['max_amount'] = $DateCommon->OutUnixByTime($post['max_amount']);
            $where[] = ['create_time','between',[$post['min_amount'],$post['max_amount']]];
        }elseif (isset($post['min_amount'])&&$post['min_amount']!=""){
            $post['min_amount'] = $DateCommon->OutUnixByTime($post['min_amount']);
            $where[] = ['create_time','egt',$post['min_amount']];
        }elseif (isset($post['max_amount'])&&$post['max_amount']!=""){
            $post['max_amount'] = $DateCommon->OutUnixByTime($post['max_amount']);
            $where[] = ['create_time','elt',$post['max_amount']];
        }

        $count = (new \app\admin\model\Shop())->getCount($where);
        $where['page'] = $post['page'];
        $list =  (new \app\admin\model\Shop())->wechatListWith("p_name,c_name,a_name",$where,"*","id desc",$post['page_number']);
        foreach ($list as &$value){
            $value['categoryList'] = (new ShopRelationCategory())->selectListWith("category_name",[['shop_id','eq',$value['id']]],"*","category_id");
        }
        return writeJson(200,['list'=>$list,'count'=>$count]);
    }

    /**
     * 商家绑定账号
     */
    public function bindaccount(Request $request){
        $post = $request->post();
        $where_admin = [
            ['id','eq',$post['use_admin_id']], //账号id
            ['status','eq',1],//状态
            ['account_type','eq',2]//账号类型
        ];
        $admin = (new Admin())->findOne($where_admin);
        if(!$admin){ throw new FailedException(['msg'=>'账号不存在']); }

        $res = (new Admin())->fieldUpdate("uid",$post['id'],$post['use_admin_id']);
        if(!$res){ throw new FailedException(['msg'=>'账号绑定失败']); }

        return writeJson(200,[],"操作成功");
    }

    /**
     * 商家审核通过  商家缴费成功之后才会有对应的仓库
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws ParameterException
     */
    public function CheckShop(Request $request){
        (new IdMustPositive())->goCheck();
        (new ActionMustPositiveValidate())->goCheck();
        $post = $request->post();
        if($post['action_type']=="check"){//审核
            $where =[['id','eq',$post['id']],['status','eq',0]];
            $count = (new \app\admin\model\Shop())->getCount($where);
            if($count==0){ throw new FailedException(['msg'=>'该商家已审核']); }
            $new =[
                'id'=>$post['id'],
                'status'=>$post['check_status'],
                'remark'=>isset($post['remark'])?$post['remark']:""
            ];
            Db::startTrans();
            $res = (new \app\admin\model\Shop())->dataUpdate($new);
            if(!$res){
                Db::rollback();
                throw new ParameterException(['msg'=>'操作失败']);
            }
            if($post['check_status']==1){ //审核通过
                //审核通过验证传来过的账号id
                if(!isset($post['use_admin_id'])){
                    throw new ParameterException(['msg'=>'审核通过需要账号id']);
                }
                $where_admin = [
                    ['id','eq',$post['use_admin_id']], //账号id
                    ['status','eq',1],//状态
                    ['account_type','eq',2]//账号类型
                ];
                $admin = (new Admin())->findOne($where_admin);
                if(!$admin){
                    Db::rollback();
                    throw new FailedException(['msg'=>'账号不存在']);
                }
                if($admin['uid']>0){
                    Db::rollback();
                    throw new FailedException(['msg'=>'账号已绑定']);
                }
                $res = (new Admin())->fieldUpdate("uid",$post['id'],$post['use_admin_id']);
                if(!$res){
                    Db::rollback();
                    throw new FailedException(['msg'=>'账号绑定失败']);
                }
            }
            Db::commit();
            return writeJson(200,[],"操作成功");
        }
    }

    /**
     * 商家提现列表
     * @param Request $request
     * @return \think\response\Json
     * @throws ParameterException
     * @throws \think\exception\DbException
     */
    public function shopWithdrawList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where = [];
        $admin = $this->admin;
        if($admin['account_type']==2){//账号类型是2 商家id 用商家的记录
            $where[] = ['a.uid','eq',$admin['uid']];
        }
        $where[] = ['a.id','gt',0];
        $where = addWhere($post,['check_status'=>'',''],$where,"1","a.");//审核状态
        $where = addWhere($post,['order_number'=>'',''],$where,"1","a.");//交易单号
        $where = addWhere($post,['name'=>'',''],$where,"1","b.");//商家名称
        //申请时间
        if(isset($post['min_time'])&&isset($post['max_time'])&&$post['min_time']!=""&&$post['max_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['a.create_time','between',[$post['min_time'],$post['max_time']]];
        }elseif (isset($post['min_time'])&&$post['min_time']!=""){
            $post['min_time'] = strtotime($post['min_time']);
            $where[] = ['a.create_time','egt',$post['min_time']];
        }elseif (isset($post['max_time'])&&$post['max_time']!=""){
            $post['max_time'] = strtotime($post['max_time']);
            $where[] = ['a.create_time','elt',$post['max_time']];
        }
        //提现金额
        if(isset($post['min_money'])&&isset($post['max_money'])&&$post['min_money']!=""&&$post['max_money']!=""){
            $where[] = ['a.withdraw_money','between',[$post['min_money'],$post['max_money']]];
        }elseif (isset($post['min_money'])&&$post['min_money']!=""){
            $where[] = ['a.withdraw_money','egt',$post['min_money']];
        }elseif (isset($post['max_money'])&&$post['max_money']!=""){
            $where[] = ['a.withdraw_money','elt',$post['max_money']];
        }

        $field = "a.id,a.order_number,a.withdraw_money,a.uid,a.check_status,b.name,b.corporate,a.create_time";
        $dataList = (new ShopWithdraw())
            ->alias("a")
            ->join("om_shop b","a.uid = b.id","right")
            ->field($field)
            ->where($where)
            ->order("a.id desc")
            ->paginate($post['page_number'], false, [
                'page' => $post['page']]);
        $dataList=$dataList->toArray();
        $count = $dataList['total'];
        $dataList = $dataList['data'];
        $returnList = [
            'count'=>$count,
            'dataList'=>$dataList
        ];
        return writeJson(200,$returnList);
    }

    /**
     * 商家申请提现
     * @param Request $request
     * @return \think\response\Json
     * @throws NoJurisdiction
     * @throws ParameterException
     * @throws FailedException
     */
    public function shopWithdrawApply(Request $request){
        (new WithdrawValidate())->goCheck();
        $admin = $this->admin;
        if($admin['account_type']!=2){
            throw new NoJurisdiction();
        }
        $post = $request->post();
        $money = (new \app\admin\model\Shop())->findOne([['id','eq',$admin['uid']]],"money");
        if($money<$post['withdraw_money']){
            throw new FailedException(['msg'=>'提现金额大于当前门店金额']);
        }
        $new = [
            'uid'=>$admin['uid'],
            'withdraw_money'=>$post['withdraw_money'],
            'order_number' =>(new ShopWithdraw())->createOrderNumber("SW"),
            'payee'        =>$post['payee'],//收款人
            'payee_account' =>$post['payee_account'],//收款人账号
            'phone'        =>$post['phone'],//电话
            'bank_name'    =>$post['bank_name'],//银行名称
            'bank_account' =>$post['bank_account']//银行账号
        ];
        $res = (new ShopWithdraw())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'提现申请失败']);
        }
        return writeJson(200,[],'提现成功');

    }
}